//
//  FeedbackViewController.m
//  HorizonLight
//
//  Created by lanou on 15/9/19.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import "FeedbackViewController.h"
#import "FeedbackScrollView.h"
#import <MessageUI/MessageUI.h>
#import "NetMoniter.h"

@interface FeedbackViewController ()<UITextFieldDelegate, MFMailComposeViewControllerDelegate,UITextViewDelegate>

@property (nonatomic, strong) FeedbackScrollView *feedbackScrollView;

@property(nonatomic,strong)NSString *title1;
@end

@implementation FeedbackViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //创建UIButton
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:(UIBarButtonItemStylePlain) target:self action:@selector(buttonClick)];
    self.navigationItem.rightBarButtonItem = rightButton;
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor blackColor];
    
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:(UIBarButtonItemStylePlain) target:self action:@selector(leftButton)];
    self.navigationItem.leftBarButtonItem = leftBarItem;
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
    
    self.feedbackScrollView = [[FeedbackScrollView alloc] initWithFrame:kBounds];
    self.feedbackScrollView.contentSize = CGSizeMake(kScreenWidth, kScreenHeight + 200);
    self.feedbackScrollView.showsVerticalScrollIndicator = NO;//隐藏竖线
    self.feedbackScrollView.scrollEnabled = YES;
    [self.view addSubview:self.feedbackScrollView];
    
    
    _feedbackScrollView.feedbackTextView.delegate = self;
    _feedbackScrollView.eMailTextField.delegate = self;
    
    [self registerForKeyboardNotifications];
}
-(void)buttonClick
{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    if (!mailClass)
    {
        [self alertWithTitle:@"当前系统版本不支持应用内发送邮件功能" Message:nil];
        return;
    }
    else if (![mailClass canSendMail])
    {
        [self alertWithTitle:@"您没有设置邮件账户" Message:nil];
        return;
    }else
    {
        if (self.feedbackScrollView.feedbackTextView.text.length == 0)
        {
            [self alertWithTitle:@"请写下您的意见" Message:nil];
        }else
        {
//            if ([NetMoniter sharedClient].isCennected)
//            {
                [self displayComposerSheet];
//            }else
//            {
//                [self alertWithTitle:@"网络不可用" Message:@"请检查网络"];
//            }
        }
    }
}

- (void)sendMailInApp
{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    if (!mailClass) {
        [self alertWithTitle:@"当前系统版本不支持应用内发送邮件功能，您可以使用mailto方法代替" Message:nil];
        return;
    }
    else if (![mailClass canSendMail]) {
        [self alertWithTitle:@"用户没有设置邮件账户" Message:nil];
        return;
    }else{
        
    }
    
}

- (void)displayComposerSheet
{
    MFMailComposeViewController *mailVC = [[MFMailComposeViewController alloc] init];
    mailVC.mailComposeDelegate = self;
    
    //设置主题
    [mailVC setSubject:@"用户反馈"];
    
    //添加收件人
    [mailVC setToRecipients:@[@"1876815514@qq.com"]];
    
    //添加密送
    [mailVC setCcRecipients:nil];

    NSString *messageBody = [NSString stringWithFormat:@"发件人:%@\n用户意见:\n%@", self.feedbackScrollView.feedbackTextView.text, self.feedbackScrollView.feedbackLabel.text];

    [mailVC setMessageBody:messageBody isHTML:NO];
    [self presentViewController:mailVC animated:YES completion:nil];
    
}

//发送提示
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    self.title1 = nil;
    NSString *message = nil;
    switch (result) {
        case MFMailComposeResultCancelled:
           self.title1 = @"取消编辑邮件";
            break;
        case MFMailComposeResultSaved:
            self.title1 = @"成功保存邮件";
            [self alertWithTitle: self.title1 Message:message];
            
            break;
        case MFMailComposeResultSent:
             self.title1 = @"发送成功";
            message = @"感谢您提出的宝贵意见，我们会更加努力";
            [self alertWithTitle: self.title1 Message:message];
            break;
        case MFMailComposeResultFailed:
             self.title1 = @"发送邮件失败";
            [self alertWithTitle: self.title1 Message:message];
            break;
        default:
            self.title1 = @"";
            break;
    }
    
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

//发送提醒
- (void)alertWithTitle:(NSString *)title Message:(NSString *)message
{
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
    [alert show];
    [self performSelector:@selector(dismissAlertView:) withObject:alert afterDelay:1.5];
    
}
- (void)dismissAlertView:(UIAlertView *)alert
{
    [alert dismissWithClickedButtonIndex:[alert cancelButtonIndex] animated:YES];
}

-(void)leftButton
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)showMessage:(NSString *)message{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
//开始输入,隐藏label
- (void)textViewDidChange:(UITextView *)textView
{
    if (0 == textView.text.length)
    {
        self.feedbackScrollView.feedbackLabel.alpha = 1;
    }else
    {
        self.feedbackScrollView.feedbackLabel.alpha = 0;
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark ---注册通知的观察者-----
-(void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChanged:) name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChanged:) name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark -----解决键盘阻挡-------
- (void)keyboardFrameChanged:(NSNotification *)notification {
    
    NSDictionary *userInfo = notification.userInfo;
    
    CGRect endFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    UIViewAnimationCurve curve = (UIViewAnimationCurve)[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
    
    CGFloat keyboardY = endFrame.origin.y;
    CGFloat screenHeight = UIScreen.mainScreen.bounds.size.height;
    
    UIScrollView *commentView = self.feedbackScrollView;
    
    [UIView animateWithDuration:duration
                          delay:0
                        options:curve << 16
                     animations:^{
                         
                         if (keyboardY == screenHeight)
                         {
                              commentView.contentOffset = CGPointMake(0, -keyboardY + screenHeight) ;
                         }else
                         {
                              commentView.contentOffset = CGPointMake(0, -keyboardY + screenHeight - 100) ;
                         }
                     }
                     completion:nil];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
